import React, { FC, useEffect, useRef, useState } from 'react'
import { Anchor, Button, Flex, Popconfirm, Tag } from 'antd'
import {
  cancelCompanycollect,
  collectCompany,
  favorCompanyList,
  getCompanyInfoOverviewIntroduction,
  getExportCompanyReport,
  getExportTaxReport
} from '@/api/companyDetail/header'
import CompanyOverview from './CompanyOverview'
import CompanyDynamic from './CompanyDynamic'
import BasicInfor from './BasicInfor'
import IntellectualProperty from './IntellectualProperty'
import { TOKEN, USERRESULT, getItem, message, setItem } from '@hs-admin/utils'
import { useSearchParams } from 'react-router-dom'
import './style.less'
import { getUserInfo } from '@/api/login'
import { DownOutlined, PlusOutlined, StarFilled, StarOutlined, UpOutlined, VerticalAlignBottomOutlined } from '@ant-design/icons'
import SpaceLayout from './CompanyDevelopment/components/SpaceLayout'
import EquityInformation from './BasicInfor/components/EquityInformation'
import SupplyDemand from './MarketConditions/SupplyDemand'
import FinancingProcess from './CompanyDevelopment/components/FinancingProcess'
import ProductionInfo from './CompanyDevelopment/components/ProductionInfo'
import ScienceProject from './CompanyDevelopment/components/ScienceProject'
import TopList from './CompanyDevelopment/components/TopList'
import Bidding from './CompanyDevelopment/components/Bidding'
import { debounce } from 'lodash'
import { MonitorsList } from '@hs-server/components'
import { addmonitorsitems, deletemonitors, has_datas } from '../../../../industryWarning/src/api/home'
import Empty from '/static/img/CompanyDetail/Empty.png'

const CompanyDetail: FC = () => {
  const [searchParams]: any = useSearchParams()
  const companyCode: string = searchParams?.get('companyCode') || ''

  const [activeComponents, setActiveComponents]: any = useState('企业概况')

  const conitorsListRef: any = useRef({})

  const [ismonitor, setismonitor] = useState(false)

  const [source_id, setsource_id] = useState('')

  const [has_monitor, sethas_monitor] = useState(false)

  const [_items, set_items]: any = useState([
    {
      key: '企业概况',
      title: '企业概况',
      iskey: true,
      components: <CompanyOverview companyCode={companyCode} />,
      children: [
        {
          key: '关于企业',
          title: '关于企业',
          href: 'disabled'
        },
        {
          key: '主营业务',
          title: '主营业务',
          href: 'disabled'
        },
        {
          key: '产业分类',
          title: '产业分类',
          href: 'disabled'
        },
        {
          key: '主要客户',
          title: '主要客户',
          href: 'disabled'
        },
        {
          key: '核心产品',
          title: '核心产品',
          href: 'disabled'
        },
        {
          key: '经营指标',
          title: '经营指标',
          href: 'disabled'
        },
        {
          key: '团队成员',
          title: '团队成员',
          href: 'disabled'
        },
        {
          key: '创新资质',
          title: '创新资质',
          href: 'disabled'
        },
        {
          key: '融资情况',
          title: '融资情况',
          href: 'disabled'
        }
      ]
    },
    {
      key: '工商信息',
      title: '工商信息',
      iskey: false,
      components: <BasicInfor companyCode={companyCode} />,
      children: [
        {
          key: '基本信息',
          title: '基本信息',
          href: 'disabled'
        },
        {
          key: '股东信息',
          title: '股东信息',
          href: 'disabled'
        },
        {
          key: '主要成员',
          title: '主要成员',
          href: 'disabled'
        },
        {
          key: '变更信息',
          title: '变更信息',
          href: 'disabled'
        }
      ]
    },
    {
      key: '投资布局',
      title: '投资布局',
      iskey: false,
      components: <SpaceLayout companyCode={companyCode} />,
      children: [
        {
          key: '投资公司',
          title: '投资公司',
          href: 'disabled'
        },
        {
          key: '分支机构',
          title: '分支机构',
          href: 'disabled'
        }
      ]
    },
    {
      key: '股权关系图',
      title: '股权关系图',
      components: <EquityInformation companyCode={companyCode} />
    },
    {
      key: '供需关系图',
      title: '供需关系图',
      components: (
        <div className="100%">
          <SupplyDemand companyCode={companyCode} />
        </div>
      )
    },
    {
      key: '融资历程',
      title: '融资历程',
      components: <FinancingProcess companyCode={companyCode} />
    },
    {
      key: '产品信息',
      iskey: false,
      title: '产品信息',
      components: <ProductionInfo companyCode={companyCode} />,
      children: [
        {
          key: '新药管线',
          title: '新药管线',
          href: 'disabled'
        },
        {
          key: '仿制药管线',
          title: '仿制药管线',
          href: 'disabled'
        },
        {
          key: '医疗器械',
          title: '医疗器械',
          href: 'disabled'
        },
        {
          key: '主要产品服务',
          title: '主要产品服务',
          href: 'disabled'
        }
      ]
    },
    {
      key: '科技项目',
      title: '科技项目',
      components: <ScienceProject companyCode={companyCode} />
    },
    {
      key: '上榜榜单',
      title: '上榜榜单',
      components: <TopList companyCode={companyCode} />
    },
    {
      key: '招投标',
      title: '招投标',
      components: <Bidding companyCode={companyCode} />
    },
    {
      key: '知识产权',
      iskey: false,
      title: '知识产权',
      components: <IntellectualProperty companyCode={companyCode} />,
      children: [
        {
          key: '专利信息',
          title: '专利信息',
          href: 'disabled'
        },
        {
          key: '软著信息',
          title: '软著信息',
          href: 'disabled'
        },
        {
          key: '商标信息',
          title: '商标信息',
          href: 'disabled'
        },
        {
          key: '资质证书',
          title: '资质证书 ',
          href: 'disabled'
        },
        {
          key: '备案网站',
          title: '备案网站 ',
          href: 'disabled'
        }
      ]
    },
    {
      key: '企业动态',
      title: '企业动态',
      components: <CompanyDynamic companyCode={companyCode} />
    }
  ])
  const [baseInfo, setbaseInfo] = useState<any>({})
  const [collect, setcollect] = useState(false)
  let userResult = getItem(USERRESULT)
  if (!getItem(TOKEN) && searchParams.get('token')) {
    setItem(TOKEN, searchParams.get('token'))
    getUserInfo({}).then((res) => {
      setItem(USERRESULT, res)
      userResult = res
    })
  } else {
    if (!getItem(USERRESULT)) {
      getUserInfo({}).then((res) => {
        setItem(USERRESULT, res)
        userResult = res
      })
    }
  }
  const getCollectList = (originBaseInfo: { companyCode: string }) => {
    favorCompanyList({ page: 1, page_size: 999 }).then((res: any) => {
      const findItem = res.items.find((ele: { company_code: any }) => ele.company_code === originBaseInfo.companyCode)
      if (findItem) {
        setcollect(true)
      } else {
        setcollect(false)
      }
    })
  }
  const callCollect = () => {
    collectCompany({ company_ids: [baseInfo.id] }).then(() => {
      message.success('收藏成功')
      getCollectList(baseInfo)
    })
  }
  const cancelCollect = () => {
    cancelCompanycollect(baseInfo.id).then(() => {
      message.success('取消收藏成功')
      getCollectList(baseInfo)
    })
  }
  const _anchorClick = (
    e: React.MouseEvent<HTMLElement>,
    link: {
      title: React.ReactNode
      href: string
    },
    item: any
  ) => {
    if (!link.href) {
      e.preventDefault()
    }
    setActiveComponents(item.key)
  }
  const handleTaxReportClick = async () => {
    const params = {
      companyCode: baseInfo.companyCode,
      companyName: baseInfo.companyName,
      userId: userResult.id
    }
    const res = await getExportTaxReport(params)
    if (res.code === 200) {
      window.open('https://aps.zhixin.net/m/taxWeb/create?clientId=1007781', '_blank')
    } else {
      message.error(res.msg)
    }
  }
  const addmonitorsitem = (id: any) => {
    if (!ismonitor) {
      addmonitors_items(id)
    } else delemonitors(id)
  }
  const getsource = (source_id: any, ismonitor: boolean) => {
    setsource_id(source_id)
    setismonitor(ismonitor)
    conitorsListRef.current.showModal(!ismonitor ? null : source_id)
  }
  const addmonitors_items = (id: any) => {
    addmonitorsitems({ data_id: source_id, list_id: id, data_name: baseInfo.companyName }).then((_res: any) => {
      message.success('监测成功')
      has_monitors()
    })
  }
  const delemonitors = (id: any) => {
    deletemonitors({ list_id: id, data_id: source_id }).then(() => {
      message.success('已取消监测')
      has_monitors()
    })
  }

  const has_monitors = async () => {
    const res = await has_datas({ data_ids: [companyCode] })
    sethas_monitor(res[companyCode])
  }

  useEffect(() => {
    getCompanyInfoOverviewIntroduction({ companyCode }).then((res: { data: { companyCode: string; companyName: string } }) => {
      setbaseInfo(res.data)
      getCollectList(res.data)
      document.title = res.data.companyName
    })
    if (searchParams.get('tab')) {
      setActiveComponents(searchParams.get('tab'))
    }

    has_monitors()
  }, [])

  useEffect(() => {
    const update = debounce(() => {
      set_items((prevState: any) => {
        prevState.forEach((item: any) => {
          if (document.getElementById(item.key)) item.count = document.getElementById(item.key)?.getAttributeNode('data-count')?.value
          item.children?.forEach((its: any) => {
            if (document.getElementById(its.key)) its.count = document.getElementById(its.key)?.getAttributeNode('data-count')?.value
            if (its.href === 'disabled') its.href = !document.getElementById(its.key) ? 'disabled' : `#${its.key}`
          })
        })
        return [...prevState]
      })
    }, 50)

    // 监听子组件DOM变更
    const observer = new MutationObserver(() => {
      update()
    })
    const targetNode = document.getElementById('z_ContentRight')

    if (targetNode) {
      observer.observe(targetNode, { childList: true, subtree: true })
    }

    return () => {
      observer.disconnect()
    }
  }, [activeComponents])

  return (
    <div className="comapny-detail-wrapper">
      <div className="w-1440px h-100vh mx-auto">
        <header>
          <Flex align="center" justify="space-between" className="center-content h-full">
            <Flex align="center" className="company-top-box pl-46px">
              <CompanyLogo baseInfo={baseInfo} />
              <h1>{baseInfo.companyName}</h1>
              <Tag color={baseInfo.isNormal ? 'green' : 'red'}>{baseInfo.isNormal ? '在营(开业)' : '未开业'}</Tag>
            </Flex>
            <Flex>
              {searchParams.get('source') === 'industryWarning' && (
                <div>
                  {!has_monitor ? (
                    <Button type="primary" shape="round" onClick={() => getsource(companyCode, false)}>
                      <PlusOutlined /> 添加监测
                    </Button>
                  ) : (
                    <Button type="primary" shape="round" onClick={() => getsource(companyCode, true)}>
                      取消监测
                    </Button>
                  )}
                </div>
              )}
              {!collect && (
                <Button className="mx-14px" type="primary" shape="round" onClick={callCollect}>
                  <StarOutlined /> 收藏企业
                </Button>
              )}
              {collect && (
                <Button className="mx-14px" type="primary" shape="round" onClick={cancelCollect}>
                  <StarFilled /> 取消收藏
                </Button>
              )}
              <Popconfirm
                title="导出企业报告"
                description={`是否导出 ${baseInfo.companyName} 企业报告`}
                onConfirm={() => {
                  getExportCompanyReport({
                    companyCode: baseInfo.companyCode,
                    companyName: baseInfo.companyName,
                    userId: userResult.id
                  }).then(() => {
                    message.open({
                      type: 'success',
                      content: (
                        <span>
                          正在导出，可在“个人中心-我的导出”下载报告
                          <Button
                            type="link"
                            onClick={() => {
                              if (searchParams.get('source') === 'financialProduct') {
                                window.open(`${import.meta.env.VITE_DATA_COMPANY_API}/PersonalCenter/myExport/companyReport`, '_blank')
                              } else if (searchParams.get('source') === 'industryWarning') {
                                window.open(`${import.meta.env.VITE_INDUSTRY_WARNING_URL}/PersonalCenter/myExport/companyReport`, '_blank')
                              } else {
                                window.open(`/PersonalCenter/myExport/companyReport`, '_blank')
                              }
                            }}>
                            立即前往
                          </Button>
                        </span>
                      ),
                      duration: 5
                    })
                  })
                }}>
                <Button type="primary" className="mx-14px" shape="round">
                  <VerticalAlignBottomOutlined /> 企业报告
                </Button>
              </Popconfirm>
              <Button type="primary" className="mx-14px" shape="round" onClick={handleTaxReportClick}>
                <VerticalAlignBottomOutlined /> 税务报告
              </Button>
            </Flex>
          </Flex>
        </header>
        <main className="tabs-main-content-wrapper pt-16px flex">
          <div className="tree-wrapper w-238px h-100% pt-24px overflow-auto" style={{ width: '238px' }}>
            {_items.map((item: any, index: number) => {
              return (
                <div
                  key={item.key}
                  className="h-40px w-100% overflow-hidden cursor-pointer line-height-40px"
                  style={{ height: `${_items[index].iskey ? 'auto' : '40px'}` }}>
                  <div className="flex items-center justify-between pl-40px pr-24px">
                    <div
                      className="contentTitle"
                      onClick={() => {
                        setActiveComponents(item.key)
                        set_items((prev: any) => {
                          prev[index].iskey = !prev[index].iskey
                          return [...prev]
                        })
                      }}>
                      {item.title}
                      {item.count?.toString()}
                    </div>
                    {item.children && (
                      <>
                        {_items[index].iskey ? (
                          <UpOutlined
                            onClick={() => {
                              set_items((prev: any) => {
                                prev[index].iskey = false
                                return [...prev]
                              })
                            }}
                          />
                        ) : (
                          <DownOutlined
                            onClick={() => {
                              set_items((prev: any) => {
                                prev[index].iskey = true
                                return [...prev]
                              })
                            }}
                          />
                        )}
                      </>
                    )}
                  </div>
                  <div className="anchor-nav coutom-anchor-style-active">
                    {item.children && (
                      <Anchor
                        affix={false}
                        getContainer={() => document.getElementById('z_ContentRight') as HTMLElement}
                        onClick={(e, link) => _anchorClick(e, link, item)}
                        items={item.children?.map((ite: any) => ({
                          ...ite,
                          href: ite.href === 'disabled' ? undefined : ite.href,
                          title: (
                            <span className={ite.href === 'disabled' ? 'disabled' : ''}>
                              {ite.title} {ite.count?.toString()}
                            </span>
                          )
                        }))}></Anchor>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
          <div className="pl-20px overflow-auto  w-1200px" id="z_ContentRight">
            {_items.map((its: any) => {
              return <div key={its.key}>{activeComponents === its.key && its?.components}</div>
            })}
            {!document.getElementById(activeComponents) ? (
              <div className="flex justify-center items-center">
                <img className="w-336px h-203px mt-200px" src={Empty} alt="" />
              </div>
            ) : null}
          </div>
        </main>
      </div>
      <MonitorsList ref={conitorsListRef} addmonitorsitem={addmonitorsitem} />
    </div>
  )
}

interface CompanyLogoProps {
  baseInfo: any
}
const CompanyLogo: React.FC<CompanyLogoProps> = (props: CompanyLogoProps) => {
  const { baseInfo } = props

  return (
    <>
      {baseInfo.iconurl && <img className="logo-img" src={baseInfo.iconurl} alt="" />}
      {!baseInfo.iconurl && baseInfo.companySname && <div className="short-name">{baseInfo.companySname}</div>}
      {!baseInfo.iconurl && !baseInfo.companySname && <img className="logo-img" src="https://datacompany.aihuoshi.net/img/logo.png" alt="" />}
    </>
  )
}

export default CompanyDetail
